"""
Case Type   : cm
Case Name   : cm_ctl encrypt对输入的密码进行加密操作异常参数验证
Create At   : 2024-07
Owner       : haomeng
Description :
    1、查看集群状态
    2、对输入的密码进行加密操作，不指定-D
    3、encrypt进行加密操作，密码为非8~15位的不合理值
Expect      :
    1、集群所有节点状态正常，显示Normal
    2、合理报错
    3、合理报错
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '需1主2备环境，否则不执行')
class CmCtl(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.comsh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.constant = Constant()

    def test_cm(self):
        text = '----step1:查看集群状态; expect:集群状态正常,DN主在节点1----'
        self.log.info(text)

        status = self.comsh.exec_cm_ctl('query', '-Cv')
        self.log.info(status)
        self.assertIn("cluster_state   : Normal", status)

        text = '----step2:对输入的密码进行加密操作，不指定-D; expect:合理报错----'
        self.log.info(text)

        encrypt_cmd1 = f'''source {macro.DB_ENV_PATH};cm_ctl encrypt;'''
        self.log.info(encrypt_cmd1)
        res1 = self.pri_user.sh(encrypt_cmd1).result()
        self.log.info(res1)
        self.assertIn('no data directory specified', res1, '加密操作执行成功')

        text = '----step3:encrypt进行加密操作，密码为非8~15位的非合理值  expect:合理报错----'
        self.log.info(text)

        passwd_list = ['enc@123', 'encrypt@12345678', '12345678', 'abcdefgh',
                       'ABCDEFGH', '!@#$*&^']
        for passwd in passwd_list:
            encrypt_cmd2 = f'''source {macro.DB_ENV_PATH};
                expect <<EOF
                spawn cm_ctl encrypt -D {macro.DB_INSTANCE_PATH};
                expect "*password:.*"
                send "{passwd}\n"
                expect eof\n''' + "EOF"
            self.log.info(encrypt_cmd2)
            res2 = self.pri_user.sh(encrypt_cmd2).result()
            self.log.info(res2)
            self.assertIn('Invalid password', res2, '加密操作执行失败')

    def tearDown(self):
        self.log.info('-----No need to clean-----')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
